<template>
  <!-- 蓝牙打印机连接组件 -->
  <view class="bluetooth-printing">
    <flex class="page-label">
      {{ status == 1 ? '蓝牙设置' : '打印' }}
    </flex>
    <view class="page-content">
      <!-- 当前蓝牙状态 -->
			<flex class="uni-form-item uni-column" justify="space-between">
				<view class="uni-label">当前蓝牙状态: </view>
				<flex class="uni-input-text" justify="flex-end">
          <view class="explain" v-if="!isEnabled">未开启</view>
          <view class="explain" v-else>已开启</view>
				</flex>
			</flex>
      <!-- 可用设备 -->
      <flex 
        class="uni-form-item uni-column" 
        direction="column" 
        align="flex-start"
      >
        <view class="uni-label">请选择打印设备: </view>
        <view class="list-explain" v-if="!devices.length && !isEnabled">请先开启手机蓝牙再重新打开本弹窗</view>
        <view class="list-explain" v-else-if="!devices.length">暂无</view>
        <template v-else>
          <flex 
            class="devices-item" 
            v-for="(item, i) in devices"
            :key="i" 
            justify="space-between"
            v-show="item.name"
          >
            <view>{{ item.name || '未知设备' }}</view>
            <button style="margin: 0" type="primary" size="mini" @click="onConn(item)">
              使用该设备打印
            </button>
          </flex>
        </template>
      </flex>
    </view>
  </view>
</template>
<script>
var tsc = require('../../utils/gprint/tsc.js')
var esc = require('../../utils/gprint/esc.js')

export default {
  name: "BluetoothPrinting",
  props: {
    status: {
      type: Number,
      default: 1 // 1: setting，2: printing
    },
    // 打印内容
    content: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
			isEnabled: false, // 蓝牙开关
      devices: [],
      currDev: null,
      connId: '',
      piaojuText:'',
      first: 1,
      senBleLabelStatus: false
    };
  },
  components: {},
  onLoad() {
		this.blueadapterCheck()
	},
  computed: {},
  methods: {

    // 蓝牙状态检查
    blueadapterCheck() {
      const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter') // 引入Java 蓝牙类
      const blueadapter = BluetoothAdapter.getDefaultAdapter()
      // 判断蓝牙是否开启
      if (blueadapter) {
        this.isEnabled = blueadapter.isEnabled()
        this.searchBle()
        uni.getStorage({
          key: 'deviceInfo',
          success: (res) => {
            this.deviceInfo = res.data
          }
        })
      } else {
        this.deviceInfo = {
          connId: '',
          currDev: ''
        }
        uni.setStorage({
          key: 'deviceInfo',
          data: this.deviceInfo
        })
      }
      uni.onBLEConnectionStateChange(() => {
        this.isEnabled = false
      })
    },

			destroyed() {
				console.log("destroyed----------")
				if (this.connId != '') {
					uni.closeBLEConnection({
						deviceId: this.connId,
						success(res) {
							console.log(res)
						}
					})
				}
			},

			searchBle() {
				var that = this
				console.log("initBule")
				uni.openBluetoothAdapter({
					success(res) {
						console.log("打开 蓝牙模块")
						console.log(res)
						that.onDevice()
						uni.getBluetoothAdapterState({
							success: function(res) {
								console.log(res)
								if (res.available) {
									if (res.discovering) {
										that.stopFindBule()
									}
									//搜索蓝牙
									//开始搜寻附近的蓝牙外围设备
									console.log("开始搜寻附近的蓝牙外围设备")
									uni.startBluetoothDevicesDiscovery({
										success(res) {
											console.log(res)
										}
									})

								} else {
									console.log('本机蓝牙不可用')
								}
							},
						})
					}
				})
			},

			onDevice(){
				console.log("监听寻找到新设备的事件---------------")
				var that = this
				//监听寻找到新设备的事件
				uni.onBluetoothDeviceFound(function(devices) {
					console.log('--------------new-----------------------'+JSON.stringify(devices))
					var re = JSON.parse(JSON.stringify(devices))
					console.log(re.devices[0].name + "  " + re.devices[0].deviceId)
						let name = re.devices[0].name
						if (
              name != "未知设备" &&
              !that.devices.find(v => v.name == name)
            ) {
							let deviceId = re.devices[0].deviceId
							that.devices.push({
								name: name,
								deviceId: deviceId,
								services: []
							})
						}
				})
			},
			
			stopFindBule() {
				console.log("停止搜寻附近的蓝牙外围设备---------------")
				uni.stopBluetoothDevicesDiscovery({
					success(res) {
						console.log(res)
					}
				})
			},
			// 连接蓝牙
			onConn(item) {
				var that = this
				console.log("连接蓝牙---------------" + item.deviceId)
        if (this.first > 1) {
          this.senBleLabel2()
          return
        }
				let deviceId = item.deviceId
				uni.createBLEConnection({
					deviceId: deviceId,
					complete(res) {
						// if (res.errMsg == "createBLEConnection:ok") {
							console.log("连接蓝牙-[" + item.name + "]--成功")
              uni.showToast({title: `连接成功，准备打印`, icon: 'success'})
							that.connId = deviceId;
							that.currDev = item
							setTimeout(function() {
								console.log('deviceId----1', deviceId)
								that.getBLEServices(deviceId, () => {
                  that.senBleLabel2()
                })
							}, 1000)
						// } else {
						// 	console.log(res)
						// }
						//连接成功 关闭搜索
						that.stopFindBule()
					},
				})
			},

      // 获取蓝牙设备所有服务
			getBLEServices(_deviceId, callBack = () => {}) {
				var that = this;
				let deviceId = _deviceId
				console.log("获取蓝牙设备所有服务(service)。---------------")

				uni.getBLEDeviceServices({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: deviceId,
					complete(res) {
						console.log('complete-res---', res)
						let serviceId = ""

						for (var s = 0; s < res.services.length; s++) {
							console.log(res.services[s].uuid)
							let serviceId = res.services[s].uuid
							uni.getBLEDeviceCharacteristics({
								// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
								deviceId: deviceId,
								// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
								serviceId: serviceId,
								success(res) {
									var re = JSON.parse(JSON.stringify(res))
									console.log('getBLEDeviceCharacteristics---', re)
									console.log('deviceId = [' + deviceId + ']  serviceId = [' + serviceId + ']')
									for (var c = 0; c < re.characteristics.length; c++) {
										if (re.characteristics[c].properties.write == true) {
											let uuid = re.characteristics[c].uuid
											console.log(' deviceId = [' + deviceId + ']  serviceId = [' + serviceId + '] characteristics=[' +
												uuid)

											for (var index in that.devices) {
												if (that.devices[index].deviceId == deviceId) {
													that.devices[index].services.push({
														serviceId: serviceId,
														characteristicId: uuid
													})
													break
												}

											}
											console.log(JSON.stringify(that.devices))
										}
									}
									callBack()
								}
							})
						}
					},
					fail(res) {
						console.log(res)
					},
				})

			},

			senBlData(deviceId, serviceId, characteristicId,uint8Array) {
        console.log('senBlData------------')
				console.log('************deviceId = [' + deviceId + ']  serviceId = [' + serviceId + '] characteristics=[' +characteristicId+ "]")
				console.log('************uint8Array=' + uint8Array)
				let uint8Buf = Array.from(uint8Array);
				function split_array(datas,size){
					var result = {};
					var j = 0
					for (var i = 0; i < datas.length; i += size) {
						result[j] = datas.slice(i, i + size)
						j++
					}
					console.log(result)
					return result
				}
				let sendloop = split_array(uint8Buf, 20);
				// console.log(sendloop.length)
				function realWriteData(sendloop, i) {
					var data = sendloop[i]
					if(typeof(data) == "undefined"){
						return
					}
					console.log("第【" + i + "】次写数据"+data)
					var buffer = new ArrayBuffer(data.length)
					var dataView = new DataView(buffer)
					for (var j = 0; j < data.length; j++) {
						dataView.setUint8(j, data[j]);
					}
					uni.writeBLECharacteristicValue({
						deviceId,
						serviceId,
						characteristicId,
						value: buffer,
						success(res) {
							realWriteData(sendloop, i + 1);
						}
					})
				}
        var i = 0;
				realWriteData(sendloop, i);
			},
      
			// senBleLabel() {
			// 	//标签模式
			// 	let deviceId = this.currDev.deviceId;
			// 	let serviceId = this.currDev.services[0].serviceId;
			// 	let characteristicId = this.currDev.services[0].characteristicId;
			// 	var command = tsc.jpPrinter.createNew()
			// 	// console.log(command)
      //   command.setSize(40, 30)
      //   command.setGap(2)
      //   command.setCls()
      //   command.setText(50, 10, "TSS24.BF2", 1, 1, "打印测试")
      //   command.setQR(50, 50, "L", 5, "A", "977767937@qq.com")
			// 	command.setPagePrint()
			// 	this.senBlData(deviceId, serviceId, characteristicId,command.getData())
			// },

			senBleLabel2() {
				//票据模式
				let deviceId = this.currDev.deviceId;
				let serviceId = this.currDev.services[0].serviceId;
				let characteristicId = this.currDev.services[0].characteristicId;
				let command = esc.jpPrinter.createNew()
				console.log('this.content---', this.content)
        if (this.first != 1) {
          command.init()
          command.setText(this.content);
          command.setPrintAndFeedRow(1)
          this.senBlData(deviceId, serviceId, characteristicId, command.getData())
        } else {
          this.first ++
          command.init()
          command.setText('');
          command.setPrintAndFeedRow(1)
          this.senBlData(deviceId, serviceId, characteristicId, command.getData())
          setTimeout(() => {
            command.setText(this.content);
          }, 2000)
        }
			},
      
      bindTextAreaBlur() {}
		}
};
</script>
<style lang="scss" scoped>
.bluetooth-printing {
  padding: 0.8rem;
  .page-content {
    max-height: 60vh;
    overflow: auto;
  }
  .uni-form-item + .uni-form-item {
    padding-top: 1.5rem;
    border-top: 1px solid #d0d0d0;
  }
  .uni-input-text {
    width: 10rem;
  }
  .devices-item {
    padding: 0.5rem 0;
    width: 100%;
  }
  .list-explain {
    margin: 2rem 0;
    width: 100%;
    text-align: center;
    color: #7b7b7b;
  }
}
</style>
